#!/usr/bin/env python 
# -*- coding:utf-8 -*-

from os import path
from queue import Queue
from threading import Thread
from lib.utils.check import *
from lib.utils.printer import *
from lib.utils.readfile import *
from lib.request.request import *
from lib.utils.settings import T_MAX,COMMONFILE_PATH

global_isNothing = True
global_result = []
class commonfile(Request):
    """
    检测敏感文件
    """
    get = "GET"
    def __init__(self,kwargs,url,data):
        Request.__init__(self,kwargs)
        self.url = url
        self.data = data
    
    def check(self):
        plus('检测敏感文件...')
        queue = Queue(T_MAX)
        for _ in range(T_MAX):
            thread = ThreadBrute(self.url,queue,self)
            thread.daemon = True
            thread.start()
        for path in readfile(COMMONFILE_PATH):
            queue.put(path.decode("utf-8"))
        queue.join()

class ThreadBrute(Thread):
    get = "GET"
    def __init__(self,target,queue:Queue,request:Request):
        Thread.__init__(self)
        self.setDaemon = True
        self.queue = queue
        self.target = target
        self.request = request
    
    def check(self):
        global global_isNothing
        global global_result
        while True:
            try:
                path = self.queue.get()
                splitUrl = SplitUrl(self.target)
                netlocUrl = splitUrl.netloc
                url = Cpath(netlocUrl,path)
                more("检测载荷:{}".format(url))
                req = self.request.Send(url=url,method=self.get)
                if req.code == 200:
                    if CEndUrl(req.url) == url:
                        global_result.append(req.url)
                        global_isNothing = False
            except Exception as e:
                print(e)
                print(path)
            finally:
                self.queue.task_done()
    def run(self):
        self.check()
def run(kwargs,url,data):
    result = {
        'commonfile':None
    }
    scan = commonfile(kwargs,url,data)
    scan.check()
    if global_isNothing:
        info_nothing()
    else:
        if global_result:
            for r in global_result:
                plus('疑似找到敏感文件: {}'.format(r))
                if not result['commonfile']:
                    result['commonfile'] = r
                else:
                    result['commonfile'] += " ," + r
    return result
